﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace JXT.PrimaryKey.Batman.Core.OAuth
{
    /// <summary>
    /// HTTP请求封装类
    /// </summary>
    public class NetHttpClient : IHttpClient
    {
        public string GetRequest(Uri uri, IDictionary<string, string> headers = null)
        {
            HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
            request.Method = "GET";
            request.ServicePoint.Expect100Continue = false;
            if (headers != null)
            {
                foreach(var item in headers){
                    request.Headers.Add(item.Key, item.Value);
                }
            }
            var response = request.GetResponse();
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                return sr.ReadToEnd();
            }
        }

        public string PostRequest(Uri uri, string data, IDictionary<string, string> headers = null)
        {
            HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
            request.Method = "POST";
            if (headers != null)
            {
                foreach (var item in headers)
                {
                    request.Headers.Add(item.Key, item.Value);
                }
            }
            using (var sw = new StreamWriter(request.GetRequestStream()))
            {
                sw.Write(data);
            }
            var response = request.GetResponse();
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                return sr.ReadToEnd();
            }
        }
    }
}
